<template>
  <a-card style="margin-top:24px;">
    <!-- 表格区域 -->
    <div class="operator">
      <a-button
        v-permission="`inspection:base:add`"
        class="mr-8"
        type="primary"
        @click="handleAddBase"
        >新增</a-button
      >
      <!-- <a-button
        v-permission="`inspection:base:batchDel`"
        type="danger"
        :class="{ 'btn-disabled': !rowSelection.selectedRowKeys.length }"
        @click="handleDelAll"
        >批量删除</a-button
      > -->
    </div>
    <a-table
      :columns="columns"
      :row-key="item => item.id"
      :pagination="pagination"
      :data-source="dataSource"
      :loading="loading"
      @change="handleTableChange"
      bordered
    >
      <span slot="action" slot-scope="item">
        <a v-permission="`inspection:base:update`" @click="handleEditBase(item)">修改</a>
        <a-divider type="vertical" />
        <a v-permission="`inspection:base:del`" class="text-danger" @click="handleDelBase(item)"
          >删除</a
        >
      </span>
    </a-table>

    <!-- 新增/修改弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form v-bind="formItemLayout" :form="form">
        <a-form-item label="考核类别">
          <a-select
            v-decorator="['inspectionType', { rules: [{ required: true, message: '请选择' }] }]"
            placeholder="请选择考核类别"
            @change="handleInspectionTypeChange"
          >
            <a-select-option
              v-for="item in dictList.inspectionType"
              :key="item.id"
              :value="item.value"
            >
              {{ item.value }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="考核汇总周期">
          <a-select
            v-decorator="['inspectionCycle', { rules: [{ required: true, message: '请选择' }] }]"
            placeholder="请选择考核汇总周期"
          >
            <a-select-option
              v-for="item in dictList.inspectionCycle"
              :key="item.id"
              :value="item.value"
            >
              {{ item.value }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="汇总周期总分">
          <a-input
            v-decorator="[
              'inspectionCycleTotalScore',
              { rules: [{ required: true, message: '请输入汇总周期总分' }] },
            ]"
            placeholder="请输入"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { basicService, inspectionService } from '@/services';

const columns = [
  {
    title: '序号',
    customRender: (text, record, index) => `${index + 1}`,
    align: 'center',
    width: 150,
  },
  {
    title: '考核类别',
    key: 'inspectionType',
    dataIndex: 'inspectionType',
    align: 'center',
  },
  {
    title: '考核汇总周期',
    key: 'inspectionCycle',
    dataIndex: 'inspectionCycle',
    align: 'center',
  },
  {
    title: '汇总周期总分',
    key: 'inspectionCycleTotalScore',
    dataIndex: 'inspectionCycleTotalScore',
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
  },
];

const formItemLayout = {
  labelCol: { span: 6, offset: 1 },
  wrapperCol: { span: 16 },
};

export default {
  name: 'inspectionBasic',

  data() {
    return {
      formItemLayout,
      columns: columns,
      dataSource: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      loading: false,
      type: 1, // 1-新增 2-修改
      visible: false,
      form: this.$form.createForm(this, { name: 'basic-form' }),
      selectedItem: null, // 修改时的选中项
      confirmLoading: false,
      rowSelection: {
        selectedRowKeys: [],
        onChange: selectedRowKeys => (this.rowSelection.selectedRowKeys = selectedRowKeys),
      },
      // 字典列表
      dictList: {
        inspectionType: [],
        inspectionCycle: [],
      },
    };
  },

  computed: {
    modalTitle() {
      return this.type === 1 ? '新增' : '修改';
    },
  },

  created() {
    this.getDict();
    this.getDataSource(this.pagination);
  },

  methods: {
    // 按需获取字典
    getDict() {
      const typeList = Object.keys(this.dictList);
      basicService.getDictByFlag({ typeList }).then(res => {
        if (res.code === '200') {
          this.dictList = res.data.typeMap;
        }
      });
    },

    // 获取数据
    getDataSource({ current, pageSize }) {
      console.log({ current, pageSize });
      this.loading = true;
      inspectionService.getBasicList({ pageNo: current, pageSize }).then(res => {
        if (res.code === '200') {
          this.dataSource = res.data.content;
          this.pagination.total = res.data.totalElements;
          this.loading = false;
        }
      });
    },

    // 分页切换
    handleTableChange(pagination) {
      console.log(pagination);
      this.getDataSource(pagination);
    },

    // 新增考核基础
    handleAddBase() {
      this.type = 1;
      this.visible = true;
    },

    // 删除考核基础
    handleDelBase(item) {
      const that = this;
      this.$confirm({
        title: '确认删除该考核基础吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          const { id } = item;
          console.log(id);
          return new Promise(resolve => {
            inspectionService
              .delBasic({ id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  that.$message.success('操作成功');
                  that.getDataSource(that.pagination);
                }
              })
              .finally(() => resolve());
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },

    // 修改考核基础
    handleEditBase(item) {
      this.type = 2;
      this.visible = true;
      this.selectedItem = item;
      this.$nextTick(() => {
        this.form.setFieldsValue({
          inspectionType: item.inspectionType,
          inspectionCycle: item.inspectionCycle,
          inspectionCycleTotalScore: item.inspectionCycleTotalScore,
        });
      });
    },

    // 选择考核类别
    handleInspectionTypeChange(value) {
      console.log('考核类别', value);
      this.form.setFieldsValue({
        inspectionType: value,
      });
    },

    // 新建/修改确认
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          console.log('Received values of form: ', values);
          if (this.type === 1) {
            inspectionService
              .addBasic(values)
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('操作成功');
                  this.visible = false;
                  this.form.resetFields();
                  this.getDataSource(this.pagination);
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          } else if (this.type === 2) {
            inspectionService
              .updateBasic({ ...values, id: this.selectedItem.id })
              .then(res => {
                if (res.code === '200') {
                  this.$message.success('操作成功');
                  this.visible = false;
                  this.selectedItem = null;
                  this.form.resetFields();
                  this.getDataSource(this.pagination);
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },

    // 取消新建
    handleCancel() {
      this.visible = false;
      this.selectedItem = null;
      this.form.resetFields();
    },

    // 批量删除
    handleDelAll() {
      console.log('批量删除', this.rowSelection.selectedRowKeys);
    },
  },
};
</script>

<style lang="less" scoped>
@import './index.less';
</style>
